package com.yan.advenced.pool;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Test;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

public class DruidTest {
    @Test
    public void testHardCode() throws Exception {
        /*
        硬编码：将数据是配置信息和Java代码耦合在一起
        1.创建DruidDataSource连接池对象
        2.设置连接池的配置信息
        3.通过连接池获取连接对象
        4.回收连接
         */

        //1.创建DruidDataSource连接池对象
        DruidDataSource dataSource = new DruidDataSource();

        //2.设置连接池的配置信息
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/stguigu");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        //非必须：
        dataSource.setInitialSize(10);
        dataSource.setMaxActive(20);
        //3.通过连接池获取连接对象
        Connection connection = dataSource.getConnection();

        //基于connection进行CRUD

        //4.回收连接
        connection.close();
    }

    @Test
    public void testResource() throws Exception {
        //1.创建properties集合，用于存储外部配置文件
        Properties properties = new Properties();

        //2.读取配置文件，获取输入流
        InputStream inputStream = DruidTest.class.getClassLoader().getResourceAsStream("db.properties");
        properties.load(inputStream);

        //3.基于Properties集合构建连接池
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);

        //4.基于连接池获取连接对象
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        //5.基于connection进行CRUD

        //6.回收连接
        connection.close();
    }

}
